引用
MediatorLiveData 是 LiveData 的子類,可以通過 MediatorLiveData 合併多個 LiveData 資料。其中任意一個 LiveData 資料發生變化,MediatorLiveData 會通知觀察他的對象。
MediatorLiveData 說明:
引用
動手改用MutableLiveData
使用 MutableLiveData
class TodoViewModel : ViewModel() {
val onNewTodo = MutableLiveData<Unit>()
private var count = 0
val todoLiveData: LiveData<List<Todo>> = MediatorLiveData<List<Todo>>().apply {
addSource(onNewTodo) {
val todo = Todo.Item("note $count", false)
this.value = this.value!! + listOf(todo)
count++
}
value = mutableListOf(Todo.Title("This is a title"))
}
}
view call todoViewModel.addNewTodo 來 postValue
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
......
val adapter = TodoAdapter()
.....
val todoViewModel = ViewModelProvider(this).get<TodoViewModel>()
......
buttonAdd.setOnClickListener {
todoViewModel.addNewTodo.postValue(Unit)
}
}
}
reference:https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData
reference:https://ithelp.ithome.com.tw/articles/10222799
reference:https://www.notion.so/LiveData-and-viewModel-9-2-bfb163f6dbfc4a71b2388538514de089